class EventBus {
  constructor() {
    this.listeners = {};
  }

  // 订阅事件
  on(eventName, callback) {
    if (!this.listeners[eventName]) {
      this.listeners[eventName] = [];
    }
    this.listeners[eventName].push(callback);
  }

  // 取消订阅事件
  off(eventName, callback) {
    if (this.listeners[eventName]) {
      this.listeners[eventName] = this.listeners[eventName].filter(cb => cb !== callback);
    }
  }

  // 触发事件
  emit(eventName, data) {
    const callbacks = this.listeners[eventName];
    if (callbacks && callbacks.length > 0) {
      callbacks.forEach(callback => callback(data));
    }
  }
}

// 创建单例实例
const eventBusInstance = new EventBus();

// 封装成以 $ 开头的对象
const $eventBus = {
  $on: eventBusInstance.on.bind(eventBusInstance),
  $off: eventBusInstance.off.bind(eventBusInstance),
  $emit: eventBusInstance.emit.bind(eventBusInstance)
};

export const $on = (eventName, callback) => eventBusInstance.on(eventName, callback)
export const $off = (eventName, callback) => eventBusInstance.off(eventName, callback)
export const $emit = (eventName, data) => eventBusInstance.emit(eventName, data)

export default $eventBus;
